package demo.view;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import demo.controler.AddressBookControler;
import demo.controler.ContactModifier;
import demo.model.AddressBook;
import demo.model.Contact;
import demo.model.ContactObserver;

public class ContactEdit extends JFrame implements ContactObserver {

	private static final long serialVersionUID = 1L;

	final JTextField lastName, firstName, phoneNumber;
	final ContactModifier action;
	
	Contact currentContact;
	

	public static ContactEdit getWindowsFor(AddressBookControler ctrl, Contact contact) {
		ContactEdit editor = new ContactEdit(ctrl.getContactUpdater(contact));
		editor.bindToContact(contact);
		return editor;
	}

	public static ContactEdit getCreateWindows(AddressBookControler ctrl) {
		ContactEdit editor = new ContactEdit(ctrl.getContactCreator());
		return editor;
	}
	
	private ContactEdit(ContactModifier contactModifier) {
		super("Edit contact");
		
		action = contactModifier;

		setLayout(new GridLayout(7, 1));
		add(LabelFactory.createHeader("Last Name"));
		add(lastName = new JTextField());
		add(LabelFactory.createHeader("First Name"));
		add(firstName = new JTextField());
		add(LabelFactory.createHeader("Phone number"));
		add(phoneNumber = new JTextField());

		JPanel pane = new JPanel();

		JButton ok = new JButton("Ok");
		ok.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				action.modify(firstName.getText(), lastName.getText(), phoneNumber.getText());
				dispose();
			}
		});
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pane.add(ok);
		pane.add(cancel);
		add(pane);
		pack();
	}

	private void bindToContact(Contact contact) {
		if (currentContact != contact) {
			currentContact = contact;
			refresh();
		}
	}

	@Override
	public void updateContact(Contact contact, AddressBook addressBook) {
		if (contact != null && currentContact == contact) {
			refresh();
		}
	}

	private void refresh() {
		Contact contact = currentContact;
		lastName.setText(contact.getLastName());
		firstName.setText(contact.getFirstName());
		phoneNumber.setText(contact.getPhoneNumber());
	}
}
